The following function searches for an element $x
from an array called $arr
by going through each element of the array, one by one. If the element is found in the array, the function returns the index of the element, otherwise, it returns -1.
Linear Search function using PHP
<?php function search($arr, $x) { for($i = 0; $i < sizeof($arr); $i++) { if($arr[$i] == $x) return $i; } return -1; } $arr = array(4, 2, 5, 6, 14, 7, 15, 3); echo search($arr, 14); ?>
More PHP Snippets
Copy Directory Content into Sub Directory using PHP
Remove duplicate values from an array using PHP
Validate Email Address using PHP
Comments